package cc.fs.myproject.utils;


import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.subjects.PublishSubject;
import rx.subjects.Subject;

/**
 * Created by fostion on 2015/7/26.
 * 封装RxAndroid进行事件订阅和发布
 */
public class EvenBus {

    private static HashMap<String, ArrayList<Subject>> publishs = new HashMap<>();//所有订阅者

    public static Subject register(String channel, Subscriber subscriber) {
        if (!publishs.containsKey(channel)) {//init and add
            ArrayList<Subject> subjects = new ArrayList<>();
            publishs.put(channel, subjects);
        }
        Log.e("----", "create");
        //subscriber msg
        Subject subject = PublishSubject.create();
        subject.observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
        publishs.get(channel).add(subject);
        return subject;
    }

    public  static void post(String channel,Object object){
        if(publishs.containsKey(channel)){
            ArrayList<Subject> subjects = publishs.get(channel);
            for(int i=0;i<subjects.size();i++) {
                subjects.get(i).onNext(object);
                Log.e("----", "post");
            }

        }
    }

    public static void unRegister(String channel, Subject subject) {
        if (publishs.containsKey(channel)) {
            if (publishs.get(channel).contains(subject)){
                publishs.get(channel).remove(subject);
                Log.e("----","unregiseter");
            }
        }
    }


}
